package com.teradata.tool;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Command {

	private ArrayList<String> stdoutLines;
	private ArrayList<String> stderrLines;
	private long runtime;

	public class Drainer implements Runnable {
		public ArrayList<String> messages;

		private InputStream ins;

		public Drainer(InputStream ins) {
			this.ins = ins;
			this.messages = new ArrayList<String>();
		}

		public void run() {
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
				String line = null;
				while ((line = reader.readLine()) != null) {
					System.out.println(line);
					messages.add(line);
				}
			} catch (Exception e) {
				System.out.println("ERROR - " + e.getMessage());
			}
		}

	}

	/** Command string */
	private String cmd;

	public Command(String cmd) {
		this.cmd = cmd;
	}

	public int exe() {
		int exitValue = 0;

		long begin = System.currentTimeMillis();

		try {
			Process process;

			String os = System.getProperty("os.name").toLowerCase();
			if (os.startsWith("win")) {
				process = Runtime.getRuntime().exec(new String[] { "cmd", "/c", cmd });
			} else {
				process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd });
			}

			Drainer stdout = new Drainer(process.getInputStream());
			Drainer stderr = new Drainer(process.getErrorStream());

			new Thread(stdout).start();
			new Thread(stderr).start();

			process.getOutputStream().close();

			exitValue = process.waitFor();
			stdoutLines = stdout.messages;
			stderrLines = stderr.messages;

		} catch (Exception e) {
			System.out.println("ERROR - " + e.getMessage());
		}

		long end = System.currentTimeMillis();
		runtime = (long) ((end - begin) / 1000f);

		return exitValue;
	}

	public ArrayList<String> getStdOut() {
		return stdoutLines;
	}

	public ArrayList<String> getStdError() {
		return stderrLines;
	}

	public long getRunSeconds() {
		return runtime;
	}
	public static void main(String arg[])
	{
		Command cmd = new Command("D:\\src\\Autotool\\AutoTool_v2.0.1\\workspace\\TD_Load.exe dbc/dbc,dbc S.T1 2 D:\\src\\Autotool\\AutoTool_v2.0.1\\workspace\\S.T1.lst -D247C -R0D0A>D:\\src\\Autotool\\AutoTool_v2.0.1\\workspace\\S.T1.log");
		cmd.exe();
		for(String str:cmd.getStdOut()){
			System.out.println(str);
		}
		
	}
}
